package com.code.springboot3.common;

import com.code.springboot3.config.JwtToken;
import com.code.springboot3.model.entity.BigUser;
import com.code.springboot3.mapper.BigUserMapper;
import com.code.springboot3.utils.JwtUtil;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.Arrays;

public class JwtRealm extends AuthorizingRealm {

    @Autowired
    private BigUserMapper bigUserMapper;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String jwtToken = (String) token.getPrincipal();
        try {
            System.out.println("Authenticating token in realm");
            Map<String, Object> claims = JwtUtil.verifyToken(jwtToken);
            Integer userId = (Integer) claims.get("id");
            Long tokenPwdVersion = JwtUtil.getPasswordVersion(jwtToken);

            BigUser user = bigUserMapper.selectById(userId);
            System.out.println("User found: " + (user != null));
            if (user == null || !user.getPwdVersion().equals(tokenPwdVersion)) {
                throw new AuthenticationException("Token invalid or expired");
            }

            return new SimpleAuthenticationInfo(user, jwtToken, getName());
        } catch (Exception e) {
            System.out.println("Authentication failed: " + e.getMessage());
            throw new AuthenticationException("Token verification failed", e);
        }
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        BigUser user = (BigUser) principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        
        System.out.println("=== Authorization Process Start ===");
        System.out.println("User ID: " + user.getId());
        System.out.println("Username: " + user.getUsername());
        System.out.println("Required roles: admin, abcd");
        System.out.println("User actual roles: " + Arrays.toString(user.getBigRole()));
        
        if (user.getBigRole() != null) {
            Set<String> roles = new HashSet<>(Arrays.asList(user.getBigRole()));
            info.setRoles(roles);
            System.out.println("Roles set in AuthorizationInfo: " + roles);
        }
        
        System.out.println("=== Authorization Process End ===");
        return info;
    }

    private boolean isAdmin(BigUser user) {
        // 这里实现判断用户是否为管理员的逻辑
        // 可以根据用户ID、角色字段等判断
        return false; // 默认返回false
    }
}
